import axios from "axios";
import Element from "element-ui"
import router from "@/router";

// axios.defaults.baseURL="http://localhost:9090"
const request=axios.create({
    timeout:5000,
    headers:{
        'Content-Type':"application/json;charset=utf-8"
    }
})

request.interceptors.request.use(config=>{
    config.headers['Authorization']=localStorage.getItem("token")
    return config
})

request.interceptors.response.use(response=>{
    let res=response.data
    if(res.code===200){
        return response;
    }
    else{
        Element.Message.error(!res.msg?'系统异常':res.msg)
        return Promise.reject(response.data.msg)
    }
},error => {
    if(error.response.status==504||error.response.status==404||error.response.status==403){
        Element.Message.error(!error.response.msg?"接口异常!":error.response.msg)
    }
    else if (error.message.includes('timeout')) {
        Element.Message.error("服务器异常！连接超时！")
    }
    else if(error.response.status===403){
        Element.Message.error(!error.response.msg?'权限不足！！':error.response.msg)
    }
    else if(error.response.status==401){
        if(localStorage.getItem("token")!=""){
            Element.Message.error("凭证已过期，请重新登录！")
            localStorage.setItem("token","")
            router.push('/login')
        }else{
            Element.Message.error(!error.response.msg?'请先登录！':error.response.msg)
            router.push('/login')
        }
    }
    return Promise.reject(error)
    }

)
export default request